﻿using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;

namespace BLL.Services
{
    public static class Serializer
    {
        /// <summary>
        /// Serializes objects into JSON
        /// </summary>
        /// <typeparam name="T">Object type</typeparam>
        /// <param name="obj">Object to be serialized</param>
        /// <returns>json string</returns>
        public static string Serialize<T>(T obj)
        {
            using (var memoryStream = new MemoryStream())
            {
                var serializer = new DataContractJsonSerializer(typeof(T));
                serializer.WriteObject(memoryStream, obj);
                memoryStream.Seek(0, SeekOrigin.Begin);
                var reader = new StreamReader(memoryStream);
                var result = reader.ReadToEnd();
                return result;
            }
        }

        /// <summary>
        /// Deserializes objects from JSON
        /// </summary>
        /// <typeparam name="T">Objects type</typeparam>
        /// <param name="jsonString">JSON string</param>
        /// <returns>Deserialized objects</returns>
        public static T Deserialize<T>(string jsonString)
        {
            using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString)))
            {
                var serializer = new DataContractJsonSerializer(typeof(T));
                return (T)serializer.ReadObject(ms);
            }
        }
    }
}
